(async function () {
  async function getDatas() {
    return fetch("https://study.duyiedu.com/api/citylist")
      .then((resp) => resp.json())
      .then((resp) => resp.data);
  }

  const doms = {
    selProvince: document.querySelector("#selProvince"),
    selCity: document.querySelector("#selCity"),
    selArea: document.querySelector("#selArea"),
  };

  // 初始化
  const datas = await getDatas();
  fillSelect(doms.selProvince, datas);
  fillSelect(doms.selCity, []);
  fillSelect(doms.selArea, []);
  regProvinceEvent();
  regCityEvent();

  function fillSelect(select, list) {
    select.className = `select ${list.length ? "" : "disabled"}`;
    const tipName = select.dataset.name;
    const span = select.querySelector(".title span");
    span.innerHTML = `请选择${tipName}`;

    select.datas = list;

    const ul = select.querySelector(".options");
    ul.innerHTML = list.map((o) => `<li>${o.label}</li>`).join("");
  }

  regCommentEvent(doms.selProvince);
  regCommentEvent(doms.selCity);
  regCommentEvent(doms.selArea);

  function regCommentEvent(select) {
    const title = select.querySelector(".title");
    title.addEventListener("click", function () {
      if (select.classList.contains("disabled")) return;
      const expands = document.querySelectorAll(".select.expand");
      for (const sel of expands) {
        if (sel !== select) {
          select.classList.remove("expand");
        }
      }
      select.classList.toggle("expand");
    });

    const ul = select.querySelector(".options");
    ul.addEventListener("click", (e) => {
      if (e.target.tagName !== "LI") return;

      const beforeActiveLi = select.querySelector("li.active");
      beforeActiveLi && beforeActiveLi.classList.remove("active");
      const li = e.target;
      li.classList.add("active");
      const span = select.querySelector(".title span");
      span.innerText = li.innerText;

      select.classList.remove("expand");
    });
  }

  function regProvinceEvent() {
    const ul = doms.selProvince.querySelector(".options");
    ul.addEventListener("click", (e) => {
      if (e.target.tagName !== "LI") return;

      const li = e.target;
      const pr = doms.selProvince.datas.find(
        (obj) => obj.label === li.innerHTML
      );
      fillSelect(doms.selCity, pr.children);
      fillSelect(doms.selArea, []);
    });
  }

  function regCityEvent() {
    const ul = doms.selCity.querySelector(".options");
    ul.addEventListener("click", (e) => {
      if (e.target.tagName !== "LI") return;

      const li = e.target;
      const pr = doms.selCity.datas.find((obj) => obj.label === li.innerHTML);
      fillSelect(doms.selArea, pr.children);
    });
  }
})();
